# coding:utf-8
"""
Author: r.xw
Date: 2023/12/9
File: user.py
"""
import logging
import re

from flask import Blueprint, make_response, session, request, url_for

from common import response_message
from common.email_utils import gen_email_code, send_email
from common.utils import ImageCode
from model.user import User

user = Blueprint("user", __name__)


@user.route('/user')
def user_index():
    pass


@user.route('/user/one')
def get_one():
    u = User()
    logging.info('这是一个info@user')
    logging.debug('这是一个debug@user')
    print(u.get_one().user_name)
    return f'{u.get_one().user_name}ok'


@user.route('/vcode')
def vcode():
    code, bstring = ImageCode().get_code()
    response = make_response(bstring)
    response.headers['content-type'] = 'image/jpeg'
    session['vcode'] = code.lower()
    return response


@user.route('/ecode', methods=['POST', 'GET'])
def email_code():
    email = request.form.get('email')
    email = request.args.get('email')
    if not re.match('\w+@\w+\.\w+', email):
        return response_message.UserMessage.error(f'邮箱格式不正确')
    code = gen_email_code()
    try:
        send_email(email, f'验证码：{code}', '邮箱验证码')
        return response_message.UserMessage.success('验证码发送成功')
    except Exception as e:
        return response_message.UserMessage.error(e)


@user.route('/logout')
def logout():
    session.clear()
    response = make_response('注销重定向', 302)
    response.headers['Location'] = url_for('index.home')
    response.delete_cookie('username')
    return response
